{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "df15a0db-6535-4090-a99b-02296ef886b6",
   "metadata": {},
   "source": [
    "Chapter 07\n",
    "# 使用嵌套for循环计算矩阵乘法\n",
    "Book_1《编程不难》 | 鸢尾花书：从加减乘除到机器学习 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "3edba36d-cd3e-4caf-82ac-f7213037b753",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义矩阵 A 和 B\n",
    "A = [[1, 2, 10, 20],\n",
    "     [3, 4, 30, 40],\n",
    "     [5, 6, 50, 60]]\n",
    "        \n",
    "B = [[4, 2],\n",
    "     [3, 1],\n",
    "     [40, 20],\n",
    "     [30, 10]]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "b9f83cfa-0941-4a68-b5c8-d9364bb09e0b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义全 0 矩阵 C 用来存放结果\n",
    "C = [[0, 0],\n",
    "     [0, 0],\n",
    "     [0, 0]]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "542fd805-bc1d-47f8-9634-a656a076e5a4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 矩阵乘法\n",
    "\n",
    "# 遍历 A 的行\n",
    "for i in range(len(A)): # len(A) 给出 A 的行数\n",
    "    \n",
    "    # 遍历 B 的列\n",
    "    for j in range(len(B[0])):  \n",
    "    # len(B[0]) 给出 B 的列数\n",
    "        \n",
    "        # 这一层相当于消去 k 所在的维度，即压缩\n",
    "        for k in range(len(B)):\n",
    "            C[i][j] += A[i][k] * B[k][j]\n",
    "            # 完成对应元素相乘，再求和"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "c241304c-8435-4f96-9976-d6e110b2d360",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1010, 404]\n",
      "[2424, 1010]\n",
      "[3838, 1616]\n"
     ]
    }
   ],
   "source": [
    "# 输出结果\n",
    "for row in C:\n",
    "    print(row)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
